package cn.endeavour.org.service.impl;

import cn.endeavour.basic.service.impl.BaseServiceImpl;
import cn.endeavour.basic.util.MD5Utils;
import cn.endeavour.basic.util.StrUtils;
import cn.endeavour.org.domain.Employee;
import cn.endeavour.org.mapper.EmployeeMapper;
import cn.endeavour.org.service.IEmployeeService;
import cn.endeavour.user.domain.LoginInfo;
import cn.endeavour.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LoginInfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;



    @Override
    @Transactional
    public void delete(Long id) {
        // 先通过id查询
        Employee employee = employeeMapper.loadById(id);
        // 删除对应表
        logininfoMapper.remove(employee.getLogininfo_id());
        super.delete(id);
    }

    @Override
    @Transactional
    public void add(Employee employee) {
        // 重构员工
        // 先添加登录表
        LoginInfo info = employee2LoginInfo(employee);
        logininfoMapper.save(info);
        // 设置
        employee.setLogininfo_id(info.getId());
        super.add(employee);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        LoginInfo info = employee2LoginInfo(employee);
        Employee dbEmployee = employeeMapper.loadById(employee.getId());
        // 设置info的id
        info.setId(dbEmployee.getId());
        // 对LoginInfo进行修改
        logininfoMapper.update(info);
        super.update(employee);
    }

    /**
     * 将员工表进行转换
     * @param employee 员工对象
     * @return dbEmployee对象
     */
    private LoginInfo employee2LoginInfo(Employee employee) {
        // 加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        // 对密码进行加密
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5Pwd);
        LoginInfo loginInfo = new LoginInfo();
        // 设置为管理员
        loginInfo.setType(0);
        BeanUtils.copyProperties(employee, loginInfo);
        return loginInfo;
    }
}
